<template>
  <el-dialog
    title="用户"
    :visible.sync="userVisible"
    width="30%"
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="userForm" label-width="80px" :rules="rules">
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="userForm.username"></el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="userForm.age" type="number"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { uuid } from "@/assets/js/utils.js";
export default {
  name: "addUser",
  props: {
    db: {
      type: IDBDatabase,
      default: null
    },
    userVisible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: "add"
    },
    form: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("年龄不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(Number(value))) {
          callback(new Error("请输入数字值"));
        } else {
          if (value < 18) {
            callback(new Error("必须年满18岁"));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    return {
      userForm: {
        username: "",
        age: "",
        email: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 1, max: 20, message: "用户名长度在1-20之内", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            pattern: /^\w+@[a-zA-Z0-9]+\.[a-zA-Z]{2,4}$/,
            message: "邮箱格式不正确",
            trigger: "blur"
          }
        ],
        age: [{ validator: checkAge, trigger: "blur" }]
      }
    };
  },
  created() {
    if (this.form.id) {
      this.userForm = this.form;
    }
  },
  methods: {
    handleClose() {
      this.$emit("update:userVisible", false);
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          let obj = this.userForm;
          if (this.db) {
            this.setIndexedBase();
            return;
          }
          if (!obj.password) {
            obj.password = "123456";
          }
          let url = this.$api.user.add;
          this.$axios({
            url,
            method: "post",
            data: obj
          }).then(res => {
            if (res.result == 200) {
              if (this.type == "upd") {
                this.$message.success("更新成功");
              } else {
                this.$message.success("添加成功");
              }

              this.handleClose();
              this.$emit("reloadList");
            }
          });
        } else {
          console.log("something wrong");
        }
      });
    },
    setIndexedBase() {
      var request = null;
      var curReq = this.$parent.getCurResult();
      if(this.type == "add"){
        request = curReq.add({ ...{ id: uuid() ,create_time:new Date()}, ...this.userForm });
      }else{
        request = curReq.put({...this.userForm });
      }
      request.onsuccess = event => {
        if (this.type == "upd") {
          this.$message.success("更新成功");
        } else {
          this.$message.success("添加成功");
        }
        this.handleClose();
        this.$emit("reloadList");
      };

      request.onerror = event=>{
        this.$message.error(event.target.error.message)
      };
    }
  }
};
</script>

<style>
</style>